<?php
/**
 * @file: xunsearchm.php
 * @User: shiwuhao
 * @Date: 16/1/5 19:54
 * @synopsis: xunSearch model类
 */

defined('BASEPATH') OR exit('No direct script access allowed');

require_once('/usr/local/xunsearch/sdk/php/lib/XS.php');

class Xunsearchm extends CI_Model
{
    // xunSearch 实例
    public $xunSearch  = NULL;
    // 配置文件目录路径
    public $iniDirPath = '/usr/local/xunsearch/sdk/php/app/';
    // 配置文件名称
    public $iniName    = 'literature.ini';
    // 配置文件绝对路径
    public $iniPath    = '';
    // 学位表名
    public $table_xw   = 'dbo_xw';
    // 期刊表名
    public $table_qk   = 'dbo_qk';
    // 会议表名
    public $table_hy   = 'dbo_hy';
    // 数据库连接
    public $wfdb       = NULL;

    public function __construct($iniName = '')
    {
        if ($iniName) $this->iniName = $iniName;

        $this->iniPath = $this->iniDirPath.$this->iniName;

        if ($this->xunSearch == NULL) {
            $this->xunSearch = new XS($this->iniPath);
        }

        $this->wfdb = $this->load->database('wfdb', true);
        $this->load->helper('url');
    }

    /**
     * 建立索引
     */
    public function buildIndex($type = '', $page = 1, $per_page)
    {
        if ($type == 'hy') { // 会议
            $this->buildIndex_hy($page, $per_page);
        } elseif ($type == 'qk') { // 期刊
            $this->buildIndex_qk($page, $per_page);
        } elseif ($type == 'xw') { // 学位
            $this->buildIndex_xw($page, $per_page);
        } else {
            exit('type 参数错误2');
        }
    }

    /**
     * 会议
     * 将表dbo_hy表中数据添加到 索引
     */
    private function buildIndex_hy($page = 1, $per_page)
    {
        $index = $this->xunSearch->index;

        if (!$per_page) $per_page = 1000;

        $start = ($page - 1) * $per_page;

        $list = $this->wfdb->select('id,ArticleID,论文题名,关键词,zz_info,出版时间,母体文献,文摘,全文路径')
            ->from($this->table_hy)
            ->where(array('id >' => $start))
            ->limit($per_page)
            ->order_by('id', 'ASC')
            ->get()
            ->result_array();

        //echo $this->wfdb->last_query();
        if (!$list) {
            exit('success');
        }

        $index->openBuffer();
        foreach($list as $k => $v) {

            $keywords    = join(' ',explode('%',$v['关键词']));
            $authors_arr = explode('%',$v['zz_info']);

            // 过滤作者信息
            foreach($authors_arr as $k => $author) {
                $author = ltrim($author, '^A');
                $offset = strpos($author, '^');
                if (!$offset) $offset = strlen($author);
                $authors_arr[$k] = substr($author,0, $offset);
            }

            $authors = join(' ', $authors_arr);

            $item = array();
            $item['id']                 = 'hy_'.$v['id'];
            $item['article_id']         = $v['ArticleID'];
            $item['title']              = $v['论文题名'];
            $item['keywords']           = $keywords;
            $item['author']             = $authors;
            $item['publication_time']   = $v['出版时间'];
            $item['journal']            = $v['母体文献'];
            $item['abstract']           = $v['文摘'];
            $item['path']               = $v['全文路径'];
            $item['db']                 = 'hy';

            $doc = new XSDocument;
            $doc   -> setFields($item);
            $index -> add($doc);
        }

        $index->closeBuffer();
    }

    /**
     * 期刊
     * 将表dbo_qk表中数据添加到 索引
     */
    private function buildIndex_qk($page = 1, $per_page)
    {
        $index = $this->xunSearch->index;

        if (!$per_page) $per_page = 1000;

        $start = ($page - 1) * $per_page;

        $list = $this->wfdb->select('id,ArticleID,F_title,f_keyword,zz_xm,f_year,qk_name,F_Abstract,全文路径')
            ->from($this->table_qk)
            ->where(array('id >' => $start))
            ->limit($per_page)
            ->order_by('id', 'ASC')
            ->get()
            ->result_array();

        //echo $this->wfdb->last_query();
        if (!$list) {
            exit('success');
        }

        $index->openBuffer();
        foreach($list as $k => $v) {

            $keywords = join(' ', explode('%',$v['f_keyword']));
            $authors  = join(' ', explode('%',$v['zz_xm']));

            $item = array();
            $item['id']                 = 'qk_'.$v['id'];
            $item['article_id']         = $v['ArticleID'];
            $item['title']              = $v['F_Title'];
            $item['keywords']           = $keywords;
            $item['author']             = $authors;
            $item['publication_time']   = $v['f_year'];
            $item['journal']            = $v['qk_name'];
            $item['abstract']           = $v['F_Abstract'];
            $item['path']               = $v['全文路径'];
            $item['db']                 = 'qk';

            $doc = new XSDocument;
            $doc   -> setFields($item);
            $index -> add($doc);
        }
        $index->closeBuffer();
    }

    /**
     * 学位
     * 将表dbo_xw表中数据添加到 索引
     */
    private function buildIndex_xw($page = 1, $per_page)
    {
        $index = $this->xunSearch->index;

        if (!$per_page) $per_page = 1000;

        $start = ($page - 1) * $per_page;

        $list = $this->wfdb->select('id,ArticleID,论文题名,关键词,作者,学位年度,文摘,全文路径')
            ->from($this->table_xw)
            ->where(array('id >' => $start))
            ->limit($per_page)
            ->order_by('id', 'ASC')
            ->get()
            ->result_array();

        //echo $this->wfdb->last_query();
        if (!$list) {
            exit('success');
        }

        $index->openBuffer();
        foreach($list as $k => $v) {

            $keywords = join(' ', explode(';',$v['关键词']));
            $authors  = join(' ', explode(';',$v['作者']));

            $item = array();
            $item['id']                 = 'xw_'.$v['id'];
            $item['article_id']         = $v['ArticleID'];
            $item['title']              = $v['论文题名'];
            $item['keywords']           = $keywords;
            $item['author']             = $authors;
            $item['publication_time']   = $v['学位年度'];
            $item['journal']            = '';
            $item['abstract']           = $v['文摘'];
            $item['path']               = $v['全文路径'];
            $item['db']                 = 'xw';

            $doc = new XSDocument;
            $doc   -> setFields($item);
            $index -> add($doc);
        }
        $index->closeBuffer();
    }

    /**
     * 根据关键词取出数据
     * @param string $keywords
     */
    public function getList($keywords = '', $page = 1, $per_page = 10)
    {
        if (!$keywords) return array('count' => 0, 'list' => array());
        $start = ($page - 1) * $per_page;

        $search = $this->xunSearch->search;

        $doc = $search
            //-> setFuzzy(true)
            -> setAutoSynonyms(true)
            -> setQuery("title:$keywords OR author:$keywords")
            -> setSort('publication_time')
            -> setLimit($per_page, $start)
            -> search();

        $count = $search->lastCount;

        $list = array();
        foreach ($doc as $k => $v) {
            if (strlen($v->publication_time) > 4) {
                $datatime = date('Y年m月d日', strtotime($v->publication_time));
            } else if (strlen($v->publication_time) == 4){
                $datatime = $v->publication_time.'年';
            }

            $list[$k]['id']                 = $v->id;
            $list[$k]['article_id']         = $v->article_id;
            $list[$k]['title']              = $v->title;
            $list[$k]['keywords']           = $v->keywords;
            $list[$k]['author']             = $v->author;
            $list[$k]['publication_time']   = $datatime;
            $list[$k]['journal']            = $v->journal;
            $list[$k]['abstract']           = $v->abstract;
            $list[$k]['path']               = $v->path;
            $list[$k]['db']                 = $v->db;
        }

        $response = array('count' => $count, 'list' => $list);
        return $response;
    }

    /**
     * 获取单条数据详情
     * @param $id
     */
    public function getDetail($id)
    {
        $xs = $this->xunSearch;

        $scheme = new XSFieldScheme();
        $scheme->addField();

        $scheme = $xs->getScheme()->getField('abstract');
        $scheme->cutlen = 0;

        $res = $xs->setScheme($scheme);
        //echo '<pre>';
        var_dump($res);




        exit('11');
        $search = $this->xunSearch->search;
        $infoObj = $search->search("id:$id");
        $infoObj = $infoObj[0];

        $info = array();
        $info['id']                 = $infoObj->id;
        $info['article_id']         = $infoObj->article_id;
        $info['title']              = $infoObj->title;
        $info['keywords']           = $infoObj->keywords;
        $info['author']             = $infoObj->author;
        $info['publication_time']   = $infoObj->publication_time;
        $info['journal']            = $infoObj->journal;
        $info['abstract']           = $infoObj->abstract;
        $info['path']               = $infoObj->path;
        $info['db']                 = $infoObj->db;

        return $info;
    }

    /**
     * 通过数据库获取单条信息
     * @param $id
     */
    public function getDetailBySql($id)
    {
        list($db,$id) = explode('_', $id);

        if (!$db || !$id) return array();

        $info = $this->wfdb->select('*')
            ->from('dbo_'.$db)
            ->where(array('id' => $id))
            ->get()
            ->row_array();

        $response = array();
        if (!$info) return array();

        if ($db == 'hy') {

            $keywords    = join(' ',explode('%',$info['关键词']));
            $authors_arr = explode('%',$info['zz_info']);

            // 过滤作者信息
            foreach($authors_arr as $k => $author) {
                $author = ltrim($author, '^A');
                $offset = strpos($author, '^');
                if (!$offset) $offset = strlen($author);
                $authors_arr[$k] = substr($author,0, $offset);
            }

            $authors = join(' ', $authors_arr);

            $response['title']      = $info['论文题名'];
            $response['author']     = $authors;
            $response['keywords']   = $keywords;
            $response['publication_time']  = $info['出版时间'];
            $response['journal']    = $info['母体文献'];
            $response['abstract']   = $info['文摘'];
            $response['path']       = $info['path'];

        } else if ($db == 'qk') {

            $keywords = join(' ', explode('%',$info['f_keyword']));
            $authors  = join(' ', explode('%',$info['zz_xm']));

            $response['title']      = $info['F_Title'];
            $response['author']     = $authors;
            $response['keywords']   = $keywords;
            $response['publication_time']  = $info['f_year'];
            $response['journal']    = $info['qk_name'];
            $response['abstract']   = $info['F_Abstract'];
            $response['path']       = $info['全文路径'];

        } else {

            $keywords = join(' ', explode(';',$info['关键词']));
            $authors  = join(' ', explode(';',$info['作者']));

            $response['title']      = $info['论文题名'];
            $response['author']     = $authors;
            $response['keywords']   = $keywords;
            $response['publication_time']  = $info['学位年度'];
            $response['journal']    = '';
            $response['abstract']   = $info['文摘'];
            $response['path']       = $info['全文路径'];
        }

        if (strlen($response['publication_time']) > 4) {
            $response['publication_time'] = date('Y年m月d日', strtotime($response['publication_time']));
        } else if (strlen($response['publication_time']) == 4){
            $response['publication_time'] = $response['publication_time'].'年';
        }

        return $response;
    }

    /**
     * 清空索引
     */
    public function clearIndex()
    {
        $index  = $this->xunSearch->index;
        $res = $index->clean();
        exit('clear success');
    }
}